import 'package:bubble_tab_indicator/bubble_tab_indicator.dart';
import 'package:extended_list/extended_list.dart';
import 'package:extended_text/extended_text.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sound/public/flutter_sound_player.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_swiper_plus/flutter_swiper_plus.dart';
import 'package:flutter_weixin/app/modules/wechat_content/compontent/bubble.dart';
import 'package:flutter_weixin/app/modules/wechat_content/compontent/extended_text/my_special_text_span_builder.dart';
import 'package:flutter_weixin/app/modules/wechat_content/compontent/hold_to_talk.dart';
import 'package:flutter_weixin/app/modules/wechat_content/compontent/wx_expression.dart';
import 'package:flutter_weixin/app/widgets/keyboard_dismisser.dart';
import 'package:flutter_weixin/app/widgets/panel.dart';
import 'package:flutter_weixin/app/widgets/primary_appbar.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import '../controllers/wechat_content_controller.dart';
import 'package:flutter_weixin/app/constant.dart';

class Message {
  final String text;
  bool isSelf = false;

  Message(this.text, this.isSelf);
}

class WechatContentView extends GetView<WechatContentController> {



  @override
  Widget build(BuildContext context) {
    return KeyboardDismisser(
      onTap: () {
        controller.panelController.hide();
        if (controller.panelController.isPanelOpen) {
          controller.panelController.close();
        }
        controller.state.value = 0;
      },
      child: SlidingUpPanel(
        //parallaxEnabled: true,
        onPanelClosed: () {
          controller.panelController.hide();
        },
        renderPanelSheet: false,
        maxHeight: 600,
        controller: controller.panelController,
        panel: Material(
          child: getPanelWidget(),
        ),
        body: Obx(
          () => Stack(
            children: [
              Scaffold(
                backgroundColor: const Color(0xFFf6f5f7),
                appBar: PrimaryAppbar.theme(backgroundColor: Colors.white),
                bottomNavigationBar: Obx(() => getBottomBar()),
                bottomSheet: bottomSheet(),
                body: Column(
                  children: [
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.only(
                            left: 12, right: 12, top: 10, bottom: 60),
                        child: Obx(
                          () => ExtendedListView.builder(
                            reverse: true,
                            itemCount: controller.messageList.length,
                            extendedListDelegate: const ExtendedListDelegate(
                                closeToTrailing: true),
                            itemBuilder: (BuildContext context, int index) {
                              return Container(
                                margin: EdgeInsets.only(bottom: 10),
                                child: Bubble(
                                  direction:
                                      controller.messageList[index].isSelf
                                          ? BubbleDirection.right
                                          : BubbleDirection.left,
                                  padding: EdgeInsets.all(10),
                                  child: ExtendedText(
                                    controller.messageList[index].text,
                                    specialTextSpanBuilder:
                                        MySpecialTextSpanBuilder(),
                                  ),
                                ),
                              );
                            },
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Offstage(
                offstage: !controller.isLongPress.value,
                child: Scaffold(
                  backgroundColor: Color(0xFF474747).withOpacity(0.7),
                  body: Stack(
                    children: [
                      Column(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          // 长按状态 0 说话中 1 删除  2 转换成文字
                          Obx(
                            () => Row(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Column(
                                  children: [
                                    if (controller.longPressState.value == 1)
                                      Container(
                                          margin: EdgeInsets.only(bottom: 10),
                                          child: Text("松开 取消",
                                              style: TextStyle(
                                                  color: Colors.white70))),
                                    AnimatedContainer(
                                        duration: Duration(milliseconds: 200),
                                        width:
                                            controller.longPressState.value == 1
                                                ? 70
                                                : 60,
                                        height:
                                            controller.longPressState.value == 1
                                                ? 70
                                                : 60,
                                        decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            color: controller
                                                        .longPressState.value ==
                                                    1
                                                ? Colors.white
                                                : Color(0xFF393939)
                                                    .withOpacity(0.8)),
                                        child: Icon(
                                          Icons.clear,
                                          color:
                                              controller.longPressState.value ==
                                                      1
                                                  ? Colors.black
                                                  : Colors.white70,
                                        )),
                                  ],
                                ),
                                SizedBox(
                                  width:
                                      (MediaQuery.of(context).size.width / 3) +
                                          30,
                                ),
                                Column(
                                  children: [
                                    if (controller.longPressState.value == 2)
                                      Container(
                                          margin: EdgeInsets.only(bottom: 10),
                                          child: Text("转文字",
                                              style: TextStyle(
                                                  color: Colors.white70))),
                                    AnimatedContainer(
                                        duration: Duration(milliseconds: 200),
                                        width:
                                            controller.longPressState.value == 2
                                                ? 70
                                                : 60,
                                        height:
                                            controller.longPressState.value == 2
                                                ? 70
                                                : 60,
                                        decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            color: controller
                                                        .longPressState.value ==
                                                    2
                                                ? Colors.white
                                                : Color(0xFF393939)),
                                        child: Icon(
                                          Icons.font_download_rounded,
                                          color:
                                              controller.longPressState.value ==
                                                      2
                                                  ? Colors.black
                                                  : Colors.white70,
                                        )),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          Obx(
                            () => Stack(
                              children: [
                                ClipPath(
                                  clipper: BottonClipper(),
                                  child: AnimatedContainer(
                                    color: controller.longPressState.value == 0
                                        ? Color(0xFFb4b4b4)
                                        : Color(0xFF393939),
                                    height: controller.voiceHeight.value,
                                    width: MediaQuery.of(context).size.width,
                                    duration: Duration(milliseconds: 200),
                                  ),
                                ),
                                if (controller.longPressState.value == 0)
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Container(
                                          margin: EdgeInsets.only(
                                              top: 10, right: 20),
                                          child: Text("松开 发送",
                                              style: TextStyle(
                                                  color: Colors.white70))),
                                    ],
                                  )
                              ],
                            ),
                          ),
                        ],
                      ),
                      Obx(
                        () => AnimatedPositioned(
                            bottom: controller.voicePositioned.value,
                            left: controller.left.value,
                            duration: Duration(milliseconds: 200),
                            child: Bubble(
                              color: controller.color.value,
                              width: controller.width.value,
                              height: controller.voiceFrameHeight.value,
                              direction: BubbleDirection.down,
                              child: Lottie.asset('assets/chat_content/voice.json'),
                            )),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget getPanelWidget() {
    return Column(
      children: [
        Container(
          width: 45,
          height: 20,
          margin: EdgeInsets.symmetric(vertical: 15),
          decoration: BoxDecoration(
              color: Color(0xFFf2f2f2),
              borderRadius: BorderRadius.circular(10)),
          child: Icon(Icons.keyboard_arrow_down_rounded),
        ),
        Container(
          margin: EdgeInsets.symmetric(horizontal: 7),
          height: 30,
          decoration: BoxDecoration(
              color: Color(0xFFe5e5e5), borderRadius: BorderRadius.circular(7)),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Padding(
                padding: EdgeInsets.only(left: 15),
                child: Icon(
                  Icons.search_outlined,
                  color: Color(0xFF979797),
                ),
              ),
              Expanded(
                child: Container(
                  // color: Colors.red,
                  alignment: Alignment.center,
                  child: TextField(
                    autofocus: true,
                    scrollPadding: EdgeInsets.only(left: 20),
                    cursorColor: Color(0xFF56bd69),
                    decoration: wxC.commonInputStyle.copyWith(
                        hintText: "搜索表情",
                        hintStyle: TextStyle(
                          color: Color(0xFF969696),
                          fontSize: 17,
                        ),
                        contentPadding: EdgeInsets.only(
                          bottom: 2,
                        )),
                  ),
                ),
              ),
            ],
          ),
        )
      ],
    );
  }

  // 获取到底部样式
  Widget getBottomBar() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Offstage(
          offstage: controller.state.value != 1,
          child: Container(
            decoration: BoxDecoration(
              color: Color(0xFFededed),
            ),
            height: 340,
            child: Column(
              children: [
                Container(
                  color: Color(0xFFf6f5f7),
                  padding: EdgeInsets.all(6),
                  child: Row(
                    children: [
                      InkResponse(
                        onTap: () async {
                          await controller.panelController.show();
                          await controller.panelController.open();
                        },
                        child: Container(
                          margin: EdgeInsets.only(right: 10),
                          width: 40,
                          height: 40,
                          padding: EdgeInsets.all(10),
                          child: SvgPicture.asset(
                              "assets/chat_content/expression_content/搜索.svg"),
                        ),
                      ),
                      Expanded(
                          child: Row(
                        children: [
                          Expanded(
                            child: Container(
                              child: TabBar(
                                  padding: EdgeInsets.zero,
                                  indicatorPadding: EdgeInsets.zero,
                                  labelPadding: EdgeInsets.zero,
                                  isScrollable: true,
                                  indicatorSize: TabBarIndicatorSize.tab,
                                  indicator: BubbleTabIndicator(
                                    indicatorHeight: 40,
                                    indicatorColor: Colors.white,
                                    tabBarIndicatorSize:
                                        TabBarIndicatorSize.tab,
                                    indicatorRadius: 10,
                                  ),
                                  tabs: controller.list
                                      .asMap()
                                      .keys
                                      .map((e) => Container(
                                            width: 40,
                                            height: 40,
                                            margin: EdgeInsets.only(
                                                right: 5, left: 5),
                                            padding: EdgeInsets.all(10),
                                            // decoration: BoxDecoration(
                                            // ),
                                            child: SvgPicture.asset(
                                                "assets/chat_content/expression_content/${controller.list[e]}.svg"),
                                          ))
                                      .toList(),
                                  controller: controller.tabController),
                            ),
                          )
                        ],
                      )),
                    ],
                  ),
                  // child: TabBarView(),
                ),
                Expanded(
                  child: TabBarView(
                    controller: controller.tabController,
                    children: [
                      Stack(
                        children: [
                          WeChatExpression((Expression expression) {
                            controller.contentController.value.text =
                                controller.contentController.value.text +
                                    "[${expression.name}]";
                            controller.contentController.value.selection =
                                TextSelection.fromPosition(TextPosition(
                                    offset: controller
                                        .contentController.value.text.length));
                            controller.contentController.refresh();
                          }),
                          Positioned(
                            bottom: 0,
                            right: 11,
                            child: Container(
                              decoration: BoxDecoration(
                                  color: Color(0xFFececec),
                                  boxShadow: [
                                    BoxShadow(
                                        color: Color(0xFFececec),
                                        offset: Offset(0, -8.0), //阴影xy轴偏移量
                                        blurRadius: 15.0, //阴影模糊程度
                                        spreadRadius: 12.0 //阴影扩散程度
                                        )
                                  ]),
                              child: Obx(
                                () => SafeArea(
                                  child: Row(
                                    children: [
                                      SizedBox(width: 20),
                                      InkResponse(
                                        onTap: () {
                                          if (controller.inputState.value) {
                                            // 特殊处理 删除表情情况
                                            String currentText = controller
                                                .contentController.value.text;
                                            String lastText =
                                                currentText.substring(
                                                    currentText.length - 1,
                                                    currentText.length);
                                            if (lastText == "]") {
                                              int indexOf =
                                                  currentText.lastIndexOf("[");
                                              if (indexOf == -1) {
                                                controller.contentController
                                                        .value.text =
                                                    controller.contentController
                                                        .value.text
                                                        .substring(
                                                            0,
                                                            controller
                                                                    .contentController
                                                                    .value
                                                                    .text
                                                                    .length -
                                                                1);
                                              } else {
                                                controller.contentController
                                                        .value.text =
                                                    controller.contentController
                                                        .value.text
                                                        .substring(0, indexOf);
                                              }
                                            } else {
                                              controller.contentController.value
                                                      .text =
                                                  controller.contentController
                                                      .value.text
                                                      .substring(
                                                          0,
                                                          controller
                                                                  .contentController
                                                                  .value
                                                                  .text
                                                                  .length -
                                                              1);
                                            }
                                          }
                                        },
                                        child: Container(
                                          width: 50,
                                          height: 40,
                                          padding: EdgeInsets.symmetric(
                                              vertical: 12),
                                          decoration: BoxDecoration(
                                              color: Colors.white,
                                              borderRadius:
                                                  BorderRadius.circular(5)),
                                          child: SvgPicture.asset(
                                            "assets/chat_content/删除.svg",
                                            color: controller.inputState.value
                                                ? Colors.black
                                                : Color(0xFFe0e0e0),
                                          ),
                                        ),
                                      ),
                                      SizedBox(width: 6),
                                      InkResponse(
                                        onTap: () {
                                          if (controller.contentController.value
                                              .text.isNotEmpty) {
                                            controller.messageList.insert(
                                                0,
                                                Message(
                                                    controller.contentController
                                                        .value.text,
                                                    true));
                                            controller.contentController.value
                                                .clear();
                                          }
                                        },
                                        child: Container(
                                          width: 50,
                                          height: 40,
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                              color: controller.inputState.value
                                                  ? Color(0xFF73ba74)
                                                  : Colors.white,
                                              borderRadius:
                                                  BorderRadius.circular(5)),
                                          child: new Text('发送',
                                              style: new TextStyle(
                                                  color: controller
                                                          .inputState.value
                                                      ? Colors.white
                                                      : Color(0xFFe0e0e0),
                                                  fontSize: 13)),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                      Center(
                        child: new Text("我的表情"),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        Offstage(
          offstage: controller.state.value != 2,
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 20, vertical: 14),
            decoration: BoxDecoration(
              border: Border(top: BorderSide(color: Color(0xFFe8e8e8))),
            ),
            height: 247,
            child: Swiper(
              loop: false,
              outer: true,
              itemBuilder: (c, i) {
                if (i == 0) {
                  return buildAddMore(chatModePage: wxC.chatModePage0);
                } else {
                  return buildAddMore(chatModePage: wxC.chatModePage1);
                }
              },
              itemCount: 2,
            ),
          ),
        ),
        Obx(
          () => Offstage(
            offstage: controller.state.value == 1,
            child: SafeArea(child: SizedBox.shrink()),
          ),
        )
      ],
    );
  }

  Widget buildAddMore({required List<ChatMoreModel> chatModePage}) {
    return GridView.count(
      physics: const NeverScrollableScrollPhysics(),
      mainAxisSpacing: 7,
      crossAxisCount: 4,
      children: chatModePage
          .map((e) => Column(
                children: [
                  Container(
                    width: 60,
                    height: 60,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(10)),
                    padding: const EdgeInsets.symmetric(vertical: 18),
                    child: SvgPicture.asset(
                      e.icon,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(e.title,
                      style: new TextStyle(
                          color: Color(0xFF989898), fontSize: 12)),
                ],
              ))
          .toList(),
    );
  }

  Widget bottomSheet() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 6, horizontal: 10),
      decoration: const BoxDecoration(
          color: Color(0xFFf6f5f7),
          border: Border(top: BorderSide(color: Color(0xFFdcdddc)))),
      child: Row(
        children: [
          InkResponse(
            onTap: () {
              int state = controller.state.value == 3 ? 0 : 3;
              controller.state.value = state;
              if (state == 0) {
                Future.delayed(Duration(milliseconds: 300), () {
                  FocusScope.of(Get.context!)
                      .requestFocus(controller.commentFocus);
                });
              }
            },
            child: Obx(
              () => SvgPicture.asset(
                "assets/chat_content/${controller.state == 3 ? '键盘' : '声音播放-线'}.svg",
                width: 25,
                height: 25,
              ),
            ),
          ),
          SizedBox(width: 10),
          Expanded(
            child: Obx(() => controller.state.value == 3
                ? HoldToTalkWidget()
                : Container(
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(7)),
                    constraints: controller.state.value == 3
                        ? BoxConstraints(
                            maxHeight: 37,
                          )
                        : null,
                    child: inputText())),
          ),
          SizedBox(width: 10),
          InkResponse(
              onTap: () {
                int state = controller.state.value == 1 ? 0 : 1;

                if (state == 1) {
                  controller.state.value = state;
                  controller.commentFocus.unfocus();
                } else {
                  Future.delayed(Duration(milliseconds: 300), () {
                    controller.state.value = state;
                  });
                  FocusScope.of(Get.context!)
                      .requestFocus(controller.commentFocus);
                }
              },
              child: Obx(
                () => SvgPicture.asset(
                  "assets/chat_content/${controller.state == 1 ? '键盘' : '表情'}.svg",
                  width: 27,
                  height: 28,
                ),
              )),
          SizedBox(width: 10),
          InkResponse(
              onTap: () {
                controller.state.value = 2;
                controller.commentFocus.unfocus();
              },
              child: SvgPicture.asset(
                "assets/chat_content/添加.svg",
                width: 25,
                height: 25,
              )),
        ],
      ),
    );
  }

  Widget inputText() {
    return ExtendedTextField(
      onEditingComplete: () {
        if (controller.contentController.value.text.isNotEmpty) {
          controller.messageList.insert(
              0, Message(controller.contentController.value.text, true));
          controller.contentController.value.clear();
        }
      },
      cursorColor: Color(0xFF56bd69),
      specialTextSpanBuilder: MySpecialTextSpanBuilder(),
      minLines: 1,
      maxLines: 5,
      textInputAction: TextInputAction.send,
      controller: controller.contentController.value,
      focusNode: controller.commentFocus,
      decoration: wxC.commonInputStyle,
    );
  }
}

class BottonClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    var path = Path();
    path.moveTo(0, size.height); //第一个点
    path.lineTo(0, 100); //第二个点
    var firstControlPoint = Offset(size.width / 2, 0); //曲线开始点
    var firstendPoint = Offset(size.width, 100); // 曲线结束点
    path.quadraticBezierTo(firstControlPoint.dx, firstControlPoint.dy,
        firstendPoint.dx, firstendPoint.dy);
    // path.lineTo(size.width, size.height-60); //第四个点
    path.lineTo(size.width, size.height); // 第五个点
    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return true;
  }
}
